package utilities;

import java.util.ArrayList;
import java.util.Collections;

public class HuffmanTreeBuilder {
	private ArrayList<HuffmanTree> trees;
	private String[] codes;
	public HuffmanTreeBuilder(double[] propabilities) {
		trees = new ArrayList<HuffmanTree>();
		for (int i=0; i<propabilities.length; i++){
			HuffmanTree tree = new HuffmanTree(i, propabilities[i]);
			trees.add(tree);
		}
		codes = new String[propabilities.length];
	}
	
	public String[] getCodes(){
		while (trees.size() > 1){
			Collections.sort(trees);
			
			HuffmanTree left = trees.remove(0);
			HuffmanTree right = trees.remove(0);
			
			HuffmanTree joint = new HuffmanTree(left, right);
			
			trees.add(joint);
		}
		
		HuffmanTree tree = trees.get(0);
		constructCode(tree, "");
//		for (int i=0; i<256; i++){
//			System.out.println("kod dla "+i+"\t"+codes[i]);
//		}
		return codes;
	}
	
	private void constructCode (HuffmanTree tree, String actualCode){
		if (tree.character != -1){
			codes[tree.character] = actualCode;
		} else {
			constructCode(tree.left, actualCode+"0");
			constructCode(tree.right, actualCode+"1");
		}
	}
}
